package com.x2.core.constant.factory;

import com.x2.base.pojo.node.LayuiTreeNode;
import com.x2.base.pojo.node.ZTreeNode;
import com.x2.core.util.MapList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 封装layui属性组件数据
 *
 * @author stylefeng
 * @Date 2019-8-26 14:01
 */
public class TreeFactory {

    /**
     * 生成layuiTree根节点
     *
     * @author stylefeng
     * @Date 2019-8-26 14:21
     */
    public static ZTreeNode createRoot() {
        ZTreeNode treeNode = new ZTreeNode();
        treeNode.setChecked(true);
        treeNode.setId(0L);
        treeNode.setName("顶级");
        treeNode.setOpen(true);
        treeNode.setPId(-1L);
        return treeNode;
    }

    /**
     * 树返回机构转换
     *
     * @param zTreeNodes
     * @return
     */
    public static List<LayuiTreeNode> convert(List<ZTreeNode> zTreeNodes) {
        List<LayuiTreeNode> resList = new ArrayList<>();
        if (zTreeNodes == null) {
            return resList;
        }
        //值转换
        List<LayuiTreeNode> dataList = convertValue(zTreeNodes);
        //构建层次结果
        MapList<Long, LayuiTreeNode> parentMap = new MapList<>();
        Map<Long, Long> childParentMap = new HashMap<>();
        for (LayuiTreeNode data : dataList) {
            parentMap.put(data.getPid(), data);
            childParentMap.put(data.getId(),data.getPid());
        }
        List<LayuiTreeNode> subList;
        for (LayuiTreeNode data : dataList) {
            subList = parentMap.get(data.getPid());
            if (subList != null && subList.size() > 0) {
                data.setChildren(parentMap.get(data.getId()));
            }
            if(!childParentMap.containsKey(data.getPid())){
                resList.add(data);
            }
        }
        return resList;
    }

    /**
     * 值转换
     *
     * @param zTreeNodes
     * @return
     */
    private static List<LayuiTreeNode> convertValue(List<ZTreeNode> zTreeNodes) {
        List<LayuiTreeNode> resList = new ArrayList<>();
        if (zTreeNodes == null) {
            return resList;
        }
        LayuiTreeNode temp;
        for (ZTreeNode z : zTreeNodes) {
            temp = new LayuiTreeNode();
            temp.setChecked(z.getChecked());
            temp.setId(z.getId());
            temp.setTitle(z.getName());
            temp.setSpread(z.getOpen());
            temp.setPid(z.getPId());
            resList.add(temp);
        }
        return resList;
    }
}
